//
//  PhotosPickerViewController.swift
//  PhotosView
//
//  Created by xxy on 16/6/4.
//  Copyright © 2016年 xxy. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
let PicturePickerMaxCount = 8
class PhotosPickerViewController: UICollectionViewController {
    /// 当前用户选中的照片索引
    private var selectedIndex = 0
    
    /// 相片数组
    lazy var pictures = [UIImage]()
 
    init() {
        super.init(collectionViewLayout: PhotoPickerLayout())
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0)

        
        // Register cell classes
        self.collectionView!.registerClass(PhotoCollectViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        // Do any additional setup after loading the view.
    }

   // MARK: - 照片选择器布局
    private class PhotoPickerLayout: UICollectionViewFlowLayout {
        
        private override func prepareLayout() {
                super.prepareLayout()
            //显示几列
            let count: CGFloat = 4
            //间距:iOS 9.0 之后，尤其是 iPad 支持分屏，不建议过分依赖 UIScreen 作为布局参照！
            // iPhone 6s- 2/iPhone 6s+ 3
            let margin = UIScreen.mainScreen().scale * 4
            let w = (collectionView!.bounds.width - (count+1)*margin) / count
            itemSize = CGSize(width: w, height: w)
            sectionInset = UIEdgeInsetsMake(margin, margin, 0, margin)
            minimumLineSpacing = margin
            minimumInteritemSpacing = margin
            }
        }
    }
    




// MARK: UICollectionViewDataSource
extension PhotosPickerViewController {
   
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return pictures.count + (pictures.count > PicturePickerMaxCount ? 0: 1)
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PhotoCollectViewCell
        cell.image = indexPath.item <  pictures.count ? pictures[indexPath.item] : nil
        
        // 设置代理
        cell.pictureDelegate = self

        return cell
    }
    
}

// MARK: - PicturePickerCellDelegate
extension PhotosPickerViewController: PicturePickerCellDelegate {
 @objc private   func picturePickerCellDidAdd(cell: PhotoCollectViewCell) {
        
        // 判断是否允许访问相册
        /**
         PhotoLibrary            保存的照片(可以删除) + 同步的照片(不允许删除)
         SavedPhotosAlbum        保存的照片/屏幕截图/拍照
         */
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
            print("无法访问照片库")
            return
        }
 // 记录当前用户选中的照片索引
        selectedIndex = collectionView?.indexPathForCell(cell)?.item ?? 0
    // 显示照片选择器
    let picker = UIImagePickerController()
    // 设置代理
    picker.delegate = self
    // picker.allowsEditing
    presentViewController(picker, animated: true, completion: nil)
    }
    
    @objc private func picturePickerCellDidRemove(cell: PhotoCollectViewCell) {
        // 1. 获取照片索引
        let indexPath = collectionView!.indexPathForCell(cell)!
//2:判断删除按钮的位置
        if  indexPath.item >= pictures.count {
        return
        }
        else {
            pictures.removeAtIndex(indexPath.item)
        }
       //3:刷新数据
        //collectionView?.deleteItemsAtIndexPaths([indexPath]) // 回去检测,前后不一致
        // reloadData只是单纯刷新数据,不会去检测具体items的数量
        collectionView?.reloadData()

    }
}

// MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate
extension PhotosPickerViewController :UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
        /// 照片选择完成
    /// - parameter info:   info 字典
    /// - 提示：一旦实现代理方法，必须自己 dismiss
    /// - picker.allowsEditing = true
    /// - 适合用于`头像`选择
    /// - UIImagePickerControllerEditedImage
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        
        let image  = info["UIImagePickerControllerOriginalImage"] as! UIImage
        //将图片缩小,节省内存
        let midImage = image.scaleToWith(400)
        //将图片添加到数组
        if  selectedIndex >= pictures.count {
            
            pictures.append(midImage)
        }
        else {
            pictures[selectedIndex] = midImage
        }
        //刷新数据
        collectionView?.reloadData()
        
        //一定要释放控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}


/// PicturePickerCellDelegate 代理
/// 如果协议中包含 optional 的函数，协议需要使用 @objc 修饰
@objc
private protocol PicturePickerCellDelegate: NSObjectProtocol {
    
    /// 添加照片
    optional func picturePickerCellDidAdd(cell: PhotoCollectViewCell)
    
    /// 删除照片
    optional func picturePickerCellDidRemove(cell: PhotoCollectViewCell)
}

/// 照片选择 Cell - private修饰类，内部的一切方法和属性，都是私有的
private class PhotoCollectViewCell: UICollectionViewCell {
    var image: UIImage? {
        didSet {
            addButton.setImage(image ?? UIImage(named: "compose_pic_big_add"), forState: .Normal)
            //隐藏关闭按钮image == nil 就是新增按钮
            removeButton.hidden = (image == nil)
        }
    }
    /// 照片选择代理
    weak var pictureDelegate: PicturePickerCellDelegate?
    // MARK: - 监听方法
    @objc func addPicture() {
        print("增加图片")
        pictureDelegate?.picturePickerCellDidAdd?(self)
    }
    @objc func removePicture() {
        print("删除照片")
        pictureDelegate?.picturePickerCellDidRemove?(self)
    }
    /// 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    /// 准备cell
    func setupUI() {
        //1:添加子空间
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        //2:设置布局
       addButton.frame = bounds
        removeButton.snp_makeConstraints { (make) in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
            //3:按钮事件监听
            addButton.addTarget(self, action: #selector(PhotoCollectViewCell.addPicture), forControlEvents: .TouchUpInside)
            removeButton.addTarget(self, action: #selector(PhotoCollectViewCell.removePicture), forControlEvents: .TouchUpInside)
        }
        
    }
    
    
    /// 懒加载
    lazy var addButton: UIButton = UIButton(imageName: "compose_pic_big_add", backImage: nil)
    /// 删除按钮
    lazy var removeButton: UIButton = UIButton(imageName: "compose_photo_close", backImage: nil)
}
    
    
  